"""
api 装饰器 主要用来装饰错误信息
"""

from typing import Any
import pydantic
from pydantic import BaseModel
import traceback
from functools import wraps
from loguru import logger


class BaseResponse(BaseModel):
    code: int = pydantic.Field(default=200, description="API status code")
    status: int = pydantic.Field(default=0, description="API status code")
    msg: str = pydantic.Field(default="success", description="API status message")
    data: Any = pydantic.Field(default=None, description="API data")
    error: str = pydantic.Field(default=None, description="内部错误 API error message")

    class Config:
        json_schema_extra = {
            "example": {
                "code": 200,
                "msg": "success",
                "status": '0'
            }
        }


def async_api_wrapper(func):
    @wraps(func)
    async def wrapper(*args, **kwargs):
        try:
            result = await func(*args, **kwargs)
        except Exception as e:
            error_msg = traceback.format_exc()
            logger.error(error_msg)
            result = BaseResponse(code=500, msg='系统错误', error=error_msg)
        return result
    return wrapper


def api_wrapper(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        try:
            result = func(*args, **kwargs)
        except Exception as e:
            error_msg = traceback.format_exc()
            logger.error(error_msg)
            result = BaseResponse(code=500, msg='系统错误', error=error_msg)
        return result
    return wrapper